<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-form-item label="业务名称" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="业务名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="咨询人数" prop="query_count">
          <el-input-number
            v-model.number="postForm.query_count"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model.number="postForm.sort"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <div class="business-data-card">
          <el-button type="primary" @click="addBusinessData">添加业务子项</el-button>
          <el-tabs type="card" style="margin-top: 10px" @tab-remove="removeBusiness" @tab-click="businessTabsClick">
            <el-tab-pane
              v-for="(item, index) in postForm.business_data"
              :key="'business_data_title' + index"
              :label="item.title"
              :name="'' + index"
              :closable="activeTabsPane === index ? false : true"
            >
              <el-form-item label="子项标题" label-width="70px">
                <el-input
                  v-model="item.title"
                  placeholder="子项标题"
                  style="width:100%"
                />
              </el-form-item>
              <el-button type="primary" style="margin-bottom: 10px" @click="addBussinessSubData(index)">添加业务子项内容</el-button>
              <div
                v-for="(sub_item, sub_index) in item.data"
                :key="'bussiness_data_sub' + item.title + sub_index"
              >
                <el-card style="margin-bottom: 10px">
                  <div slot="header">
                    <span>{{ item.title }} 子项内容 {{ sub_index }}</span>
                    <el-button type="text" style="float: right;padding: 3px 0;color: red" @click="removeBusinessSubData(index, sub_index)">删除</el-button>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="主标题">
                        <el-input
                          v-model="sub_item.title"
                          placeholder="主标题"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="副标题">
                        <el-input
                          v-model="sub_item.sub_title"
                          placeholder="副标题"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="内容">
                    <el-input
                      v-model="sub_item.content"
                      type="textarea"
                      placeholder="内容"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-card>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import { getBusinessByID, addBusiness, editBusiness } from '@/api/business'

const fields = {
  title: '业务名称'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'BusinessDetail',
  components: { Sticky },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      postForm: {
        title: '',
        query_count: 0,
        business_data: [],
        sort: 1,
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '业务名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      },
      activeTabsPane: 0
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const business = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addBusiness(business).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              business.id = this.id
              editBusiness(business).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getBusinessByID() {
      if (this.id !== 0) {
        getBusinessByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            return
          }
          const {
            title,
            query_count,
            sort,
            status,
            business_data
          } = response.data
          this.postForm = {
            title,
            query_count,
            sort,
            status,
            business_data
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.postForm.business_data = []
      this.loading = false
    },
    addBusinessData() {
      this.postForm.business_data.push({
        title: '请填写子项标题',
        data: []
      })
    },
    addBussinessSubData(index) {
      if (!this.postForm.business_data[index].title || this.postForm.business_data[index].title === '请填写子项标题') {
        this.$confirm('请填写子项标题').then(() => {}).catch(() => {})
        return
      }
      this.postForm.business_data[index].data.push({
        title: '',
        sub_title: '',
        content: ''
      })
    },
    removeBusiness(target_name) {
      // console.log(target_name)
      this.postForm.business_data.splice(parseInt(target_name), 1)
    },
    removeBusinessSubData(index, sub_index) {
      this.postForm.business_data[index].data.splice(sub_index, 1)
    },
    businessTabsClick(event) {
      // console.log(event)
      this.activeTabsPane = parseInt(event.name)
    }
  }
}
</script>

<style lang="scss" scoped>
// .business-data-card >>> .el-tabs__item {
//   padding-left: 0px !important;
// }
// .business-data-card__title >>> .el-input__inner {
//   border: none !important;
//   height: 95% !important;
// }
</style>
